package com.xiaobai.service.imageRecognition;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobai.service.addition.HealthReportService_v2;
import com.xiaobai.units.HttpUnits;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-12-11
 **/

@Slf4j
@Service("validCodeService")
public class ValidCode implements IValidCode {

    private CloseableHttpClient httpclient = HttpClients.createDefault();
    private static ThreadLocal<Pair<String, byte[]>> imageBytesThreadLocal = new ThreadLocal<>();

    @Override
    public String figureCaptcha(byte[] imageBytes) {
        String code = this.imageCodeDiscernDog(imageBytes);
        imageBytesThreadLocal.set(new Pair<>(code, imageBytes));
        return code;
    }

    @Override
    public void saveImageFile() {
        String code = imageBytesThreadLocal.get().getKey();
        byte[] imageBytes = imageBytesThreadLocal.get().getValue();
        if (imageBytes == null || imageBytes.length == 0) {
            log.error("传入的图像字节数组为空");
            return;
        }
        // 随意定义4个字母即可
        String filePah = HealthReportService_v2.IMAGES_PATH + code + "_" + (System.currentTimeMillis() / 1000) + ".png";
        File file = new File(filePah);
        FileOutputStream os;
        try {
            os = new FileOutputStream(file);
            os.write(imageBytes, 0, imageBytes.length);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cancelSave() {
        imageBytesThreadLocal.remove();
    }

    /**
     * 需要自动存储成功的训练集,那边验证成功后,再次传入得以存储
     *
     * 图鉴
     * 打码狗
     * 滴滴答题
     * python
     */

    public String imageCodeDiscern(byte[] bytes) throws IOException {
        //用户名
        String username= "13723574890";
        //密码
        String password= "1111qqqq";
        HttpPost httpPost = new HttpPost("http://api.ttshitu.com/predict");
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("username",username);
        paramsMap.put("password", password);
        paramsMap.put("typeid", "3");
        paramsMap.put("image", JSON.toJSONString(bytes));
        UrlEncodedFormEntity formEntity = HttpUnits.generateEntity(paramsMap);
        httpPost.setEntity(formEntity);
        try (CloseableHttpResponse rsp = httpclient.execute(httpPost);){
            // 内部会自动关闭输入流
            String content = EntityUtils.toString(rsp.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(content);
            if (jsonObject.getBoolean("success")) {
                return jsonObject.getJSONObject("data").getString("result");
            }
        }catch (SocketException e){
            // 连接失效,进行重试
            log.error(e.getMessage());
            return null;
        }
        return null;
    }

    /**
     * 打码狗平台
     */
    public String imageCodeDiscernDog(byte[] bytes) {
        HttpPost httpPost = new HttpPost("http://www.damagou.top/apiv1/recognize.html");
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("userkey","47e294828282e4d70fd7d17fc4d665e2");
        paramsMap.put("typeid", "1001");
        paramsMap.put("image", JSON.toJSONString(bytes));
        paramsMap.put("isJson", "2");
        UrlEncodedFormEntity formEntity = HttpUnits.generateEntity(paramsMap);
        httpPost.setEntity(formEntity);
        try (CloseableHttpResponse rsp = httpclient.execute(httpPost)){
            // 内部会自动关闭输入流
            String content = EntityUtils.toString(rsp.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(content);
            if (jsonObject.getString("status").equals("0")) {
                String code = jsonObject.getString("data");
                // 存入文件
                return code;
            }
            log.error("验证码获取失败,错误:" + jsonObject.getString("msg"));
        }catch (SocketException e){
            // 连接失效,进行重试
            log.error(e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 滴答打码平台 http://www.dididati.com
     */
    public String imageCodeDiscernDiDa(byte[] bytes) {
        HttpPost httpPost = new HttpPost("http://api.dididati.com/v3/upload/base64");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        Map<String,String> paramsMap = new HashMap<>();
        paramsMap.put("userkey","838bdfaf726f73ad3882b662cf33c9b0d54bb5dec364d931");
        paramsMap.put("type", "8001");
        paramsMap.put("image", JSON.toJSONString(bytes));
        paramsMap.put("isJson", "2");
        UrlEncodedFormEntity formEntity = HttpUnits.generateEntity(paramsMap);
        httpPost.setEntity(formEntity);
        try (CloseableHttpResponse rsp = httpclient.execute(httpPost);){
            // 内部会自动关闭输入流
            String content = EntityUtils.toString(rsp.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(content);
            if (jsonObject.getString("err").equals("0")) {
                // 存入文件
                return jsonObject.getJSONObject("result").getString("code");
            }
            log.error("验证码获取失败,错误:" + content);
        }catch (SocketException e){
            // 连接失效,进行重试
            log.error(e.getMessage());
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
